/**
* 作者 ：sunmeng
*
* 日期 ：2017/11/14
*
* 描述 ：目录管理
*/
<template>
  <el-container class="is-vertical">
  	<HeaderBar :menuState="menuState" v-if="true"></HeaderBar>
    <BreadCrumb :options="breadOptions" class="breadcreamb"></BreadCrumb>
  	<el-container class="is-horizontal catalogContainer">
	    <el-aside>
	    	<div class="treeBar">
					<div class="treeTitle">
						<h5>数据资源分类</h5>
						<el-button type="primary" size="mini" @click="show" v-text="message">{{ message }}</el-button>
					</div>
	    		<TreeBar :options="treeOptions" class="catalogTree"></TreeBar>
	    	</div>
	    </el-aside>
	    <el-main>
        <ModuleBar :title="moduleBarTitle"></ModuleBar>
        <MTable :options="tableOptions" ref="myTable" class="tablebar sourceData"></MTable>
      </el-main>
    </el-container>
    <Dialog :options="dialogOptions" class="addRoleDialog">
      <CheckFailForm slot="dialogContent" v-if="dialogOptions.visible">
        <MTable :options="failData" slot="failDetail" style="min-width: 0;" class="failDataTable"></MTable>
      </CheckFailForm>
    </Dialog>
    <Dialog :options="dialogOptions2">
      <AddCatalogTypeForm slot="dialogContent" :parentModel="catalogManageModel" :addCatalogTypeFormData="addCatalogTypeFormData" v-if="dialogOptions2.visible"></AddCatalogTypeForm>
    </Dialog>
  </el-container>
</template>
<script>
  import config from '../../config/config'
  import dirAPIs from '../../api/dirAPIs'
  import departmentAPIs from '../../api/departmentAPIs'
  import HeaderBar from '../../components/header/Header.vue'
  import TreeBar from '../../components/treebar/TreeBar.vue'
  import BreadCrumb from '../../components/breadcrumb/BreadCrumb.vue'
  import ModuleBar from '../../components/modulebar/ModuleBar.vue'
  import MTable from '../../components/table/Table.vue'
  import Dialog from '../../components/dialog/Dialog.vue'
  import CheckFailForm from './components/inputTemplate/CheckFailForm.vue'
  import AddCatalogTypeForm from './components/addCatalogTypeForm/AddCatalogTypeForm.vue'

  export default {
    name: 'main',
    components: {
    	HeaderBar,
    	TreeBar,
    	BreadCrumb,
      ModuleBar,
      MTable,
      Dialog,
      CheckFailForm,
      AddCatalogTypeForm
    },
    data () {
      return {
        menuState: '/catalogManage/main',
        moduleBarTitle: "信息资源",
        treeOptions: {
        	see: false,
        	data:[
        	],
        	treeMethod:{
        		append(node, data, store){

        		},
        		remove(node, data, store){

        		},
            nodeClick () {}
        	}
        },
        breadOptions:{
        	bread:[
            {
              label:"政务数据资源管理系统",
              path:"/"
            },{
              label:"目录管理",
              path:"/catalogManage/main"
            }
        	]
        },
        message: "管理",
        tableOptions: {
        	handleSelectionChange (rows) {

          }
        },
        failData: {
          handleSelectionChange (rows) {

          },
          data: [{
            id: "1",
            templateName: "模板一",
            question: "C7内容错误，请填写“是”或“否”。"
          },{
            id: "2",
            templateName: "模板二",
            question: "D9内容错误，应为数字字母组合。"
          }],
          thead: [{
            prop: "id", // 数据的key值
            label: "序号", // 显示的标题
            width: 120
          },{
            prop: "templateName", // 数据的key值
            label: "模板名称", // 显示的标题
            width: 200
          },{
            prop: "question", // 数据的key值
            label: "问题描述" // 显示的标题
          }],
          size: "mini"
        },
        dataTypeList: [
          {
            value: 1,
            label: "数据库"
          },
          {
            value: 2,
            label: "电子文件"
          },
          {
            value: 3,
            label: "表格"
          }
        ],
        dialogOptions: {
          visible: false,
          title: "模板校验"
        },
        dialogOptions2: {
          visible: false,
          title: "添加资源分类"
        },
        createTimeToStart: +new Date("1971/01/01 00:00:00"),
        createTimeToEnd: +new Date("2030/01/01 00:00:00"),
        catalogManageModel: this,
        addCatalogTypeFormData: {},
        dirId: "", // 全局选择目录分类ID
        dirTypeId: "", // 目录分类ID的根级ID
        allDirIdArr: [], // 当前目录的所有上一级集合
        allDirId: "", // 当前目录的所有上一级集合
        deparmentData: [] // 部门数据
      }
    },
    mounted: function () {
    	let vm = this

      vm.resetSearch()

      // 信息资源分类
      vm.loadTreeData()
      // 加载提供方数据
//      vm.loadDepartmentData()
      vm.dirTypeId = 3
      // 加载初始资源数据
      vm.loadData({
        token: localStorage.token,
        pageNum: 1,
        pageSize: 20,
        dirTypeId: vm.dirTypeId,
        createTimeToStart: vm.createTimeToStart,
        createTimeToEnd: vm.createTimeToEnd
      })
		},
    methods: {
      resetSearch () {
        let vm = this
        let params = {
          resourceName: "",
          resourceCode: "",
          departmentId: "",
          status: "",
          createTimeToStart: "",
          createTimeToEnd: ""
        }
        // 查询条件记录到状态树
        vm.$store.dispatch('searchTable', params)
      },
      loadTreeData () {
        let vm = this
        dirAPIs.list({
          token: localStorage.token
        }).then(({ data }) => {
          if(data.code == 10000){
            vm.initTree(data.data)
          }
        })
      },
      // 为了区分dirId和dirTypeId而写的冗余方法
      loadDirData(){
        let vm = this
        let vuex = vm.$store.state.catalogManage.pages.main
        if(!vm.dirId) {
          vm.loadData({
            token: localStorage.token,
            pageNum: vm.tableOptions.pageInfo.currentPage,
            pageSize: vm.tableOptions.pageInfo.pageSize,
            dirTypeId: vm.dirTypeId,
            name: vuex.resourceName,
            code: vuex.resourceCode,
            departmentId: [...vuex.departmentId].pop(),
            status: vuex.status,
            createTimeToStart: +vuex.createTimeToStart || vm.createTimeToStart,
            createTimeToEnd: +vuex.createTimeToEnd>0?+vuex.createTimeToEnd+24*60*60*1000:"" || vm.createTimeToEnd
          })
        }
        else {
          vm.loadData({
            token: localStorage.token,
            pageNum: vm.tableOptions.pageInfo.currentPage,
            pageSize: vm.tableOptions.pageInfo.pageSize,
            dirId: vm.dirId,
            name: vuex.resourceName,
            code: vuex.resourceCode,
            departmentId: [...vuex.departmentId].pop(),
            status: vuex.status,
            createTimeToStart: +vuex.createTimeToStart || vm.createTimeToStart,
            createTimeToEnd: +vuex.createTimeToEnd>0?+vuex.createTimeToEnd+24*60*60*1000:"" || vm.createTimeToEnd
          })
        }
      },
      loadData(params) {
        let vm = this
        dirAPIs.infoResourceList(params).then(({data}) => {
//          console.log(data)
          if (data.code == 10000) {
            data.data.map(item => {
              if(item.status==2||item.status==4)
                item["disabledBtn"] = "提交"
            })
//            console.log(data.data)
            vm.initTable(data.data, params.pageNum, params.pageSize, data.total)
          }
        })
      },
    	initTree(dataList) {
    		let vm = this
    		vm.treeOptions = {
    			see:false,
    			data:dataList,
          expandAll: true,
    			treeMethod:{
		      	append(node, data, store) {
			        vm.dialogOptions2.visible = true
              vm.addCatalogTypeFormData = {
			          node: node,
                data: data
              }
		        },
		        remove(node, data, store) {
			        vm.$confirm(`确定要删除【${data.label}】吗?`,'提示',{
			        	cancelButtonText:'取消',
			        	confirmButtonText:'确定',
			        }).then(() => {
			          dirAPIs.delete({
                  token: localStorage.token,
                  key: data.value
                }).then(res => {
//			            debugger
			            if(res.data.code == 10000) {
                    vm.$message.success('删除信息资源分类成功！')

                    const parent = node.parent;
                    const children = parent.data.children || parent.data;
                    const index = children.findIndex(d => d.value === data.value);
//                    debugger
                    children.splice(index, 1);
                  }
                  else{
                    vm.$message.error(res.data.msg)
			              vm.dialogOptions2.visible = false
                  }
                })

			        }).catch(() => {
			        	vm.$message.info('已取消');
			        })
		        },
            nodeClick(node, nodeObj, component) {
//		      	  debugger
              let pageNo = 1,
                pageSize = 20

              vm.dirId = node.value
              vm.dirTypeId = node.rootId
              vm.allDirIdArr = []
              vm.getParent(nodeObj)
              vm.allDirId = vm.allDirIdArr.reverse().join("")
//              debugger
              if(node.rootId) {
                vm.loadData({
                  token: localStorage.token,
                  pageNum: pageNo,
                  pageSize: pageSize,
                  dirId: node.value,
                  createTimeToStart: vm.createTimeToStart,
                  createTimeToEnd: vm.createTimeToEnd
                })
              }
              else{
                vm.loadData({
                  token: localStorage.token,
                  pageNum: pageNo,
                  pageSize: pageSize,
                  dirTypeId: node.value,
                  createTimeToStart: vm.createTimeToStart,
                  createTimeToEnd: vm.createTimeToEnd
                })
              }
            }
		      }
    		}
    	},
      getParent(parent){
        let vm = this
//        debugger
        if(parent!=null&&parent.data&&parent.data.code) {
          vm.allDirIdArr.push(parent.data.code)
          vm.getParent(parent.parent)
        }
      },
    	show () {
    		if(this.message=="管理"){
    			this.message = "取消"
    			this.treeOptions.see = true
    		}else{
    			this.message = "管理"
    			this.treeOptions.see = false
    		}
    	},
      initTable (dataList, pageNo, pageSize, total) {
        let vm = this
        let vuex = vm.$store.state.catalogManage.pages.main
        //必须先加载部门树，不然组件渲染不出来
        departmentAPIs.listTree({
          token: localStorage.token
        }).then(({ data }) => {
          if(data.code == 10000) {
            vm.deparmentData = data.data
            vm.tableOptions = {
              thead: [{
                prop: "infoResourceCode", // 数据的key值
                label: "信息资源代码" // 显示的标题
              },{
                prop: "infoResourceName", // 数据的key值
                label: "信息资源名称" // 显示的标题
              },{
                prop: "departmentName", // 数据的key值
                label: "提供方" // 显示的标题
              },{
                prop: "abstracts", // 数据的key值
                label: "信息资源摘要" // 显示的标题
              },{
                prop: "status", // 数据的key值
                label: "资源状态", // 显示的标题
                formatter (row, column, cellValue) {
                  switch (cellValue) {
                    case 1 :
                      return "新增未提交"
                      break
                    case 2 :
                      return "已提交待审核"
                      break
                    case 3 :
                      return "审核未通过"
                      break
                    case 4 :
                      return "审核通过已发布"
                      break
                  }
                }
              },{
                prop: "createTime", // 数据的key值
                label: "创建时间" // 显示的标题
              }],
              operation:{
                items: [{
                  xtype: "link",
                  buttonType: "danger", // 按钮样式
                  buttonText: "编辑资源",
                  onClick (i, row) {
                    vm.$router.push({ path: '/catalogManage/resources', query: { infoResourceId: row.infoResourceId }});
                  }
                },{
                  xtype: "link",
                  buttonType: "danger", // 按钮样式
                  buttonText: "编辑项",
                  onClick (i, row) {
                    vm.$router.push({path: '/catalogManage/term', query: { infoResourceId: row.infoResourceId }});
                  }
                },{
                  xtype: "link",
                  buttonType: "danger", // 按钮样式
                  buttonText: "提交",
                  onClick (i, row) {
                    dirAPIs.infoResourceSubmitCheck({
                      token: localStorage.token,
                      key: row.infoResourceId
                    }).then(({ data }) => {
                      if(data.code == 10000) {
                        vm.$message.success("提交审核成功！")
                        // 刷新表格
                        vm.loadDirData()
                      }
                      else {
                        vm.$message.error("提交审核失败！")
                      }
                    })
                  }
                },{
                  xtype: "link",
                  buttonType: "primary", // 按钮样式
                  buttonText: "删除",
                  onClick (i, row) {
                    dirAPIs.infoResourceDelete({
                      token: localStorage.token,
                      key: row.infoResourceId
                    }).then(({ data }) => {
                      if(data.code == 10000) {
                        vm.$message.success("删除资源成功！")
                        // 刷新表格
                        vm.loadDirData()
                      }
                      else {
                        vm.$message.error(data.msg)
                      }
                    })
                  }
                }]
              },
              data: dataList,
              pageInfo: {
                currentPage: pageNo,
                pageSizes: [20, 40, 60, 80],
                pageSize: pageSize,
                layout: "prev, pager, next, total, sizes, jumper",
                total: total,
                handleSizeChange (val) {
                  vm.tableOptions.pageInfo.pageSize = val
                  vm.loadDirData()
                },
                handleCurrentChange (val) {
                  vm.tableOptions.pageInfo.currentPage = val
                  vm.loadDirData()
                }
              },
              handleSelectionChange (rows) {
                vm.tableRows = rows
              },
              selection: {
                width: 55
              },
              toolbar: [{
                xtype: "toolbarRow",
                items: [{
                  xtype: "text",
                  defaultText: "信息资源名称",
                  ref: "resourceName",
                  style: "width:145px;",
                  containerStyle: "width:145px;margin-right: 2%;",
                  value: vuex.resourceName
                },{
                  xtype: "text",
                  defaultText: "信息资源代码",
                  ref: "resourceCode",
                  style: "width:145px;",
                  containerStyle: "width:145px;margin-right: 2%;",
                  value: vuex.resourceCode
                },{
                  xtype: "cascader",
                  ref: "departmentId",
                  data: vm.deparmentData,
                  style: "width:145px;",
                  containerStyle: "width:145px;margin-right: 2%;",
                  value: vuex.departmentId
                },{
                  xtype: "select",
                  defaultText: "资源状态",
                  ref: "status",
                  data: [{
                    value: "1",
                    label: "新增未提交",
                  },{
                    value: "2",
                    label: "已提交待审核",
                  },{
                    value: "3",
                    label: "审核未通过"
                  },{
                    value: "4",
                    label: "审核通过已发布"
                  }],
                  valueKey: vuex.status,
                  style: "width:145px;",
                  containerStyle: "width:145px;margin-right: 2%;"
                },{
                  xtype: "datepicker",
                  defaultText: "起始时间",
                  value: vuex.createTimeToStart==""?"":new Date(vuex.createTimeToStart),
                  ref: "startTime",
                  style: "width:145px;",
                  containerStyle: "width:145px;margin-right: 2%;"
                },{
                  xtype: "datepicker",
                  defaultText: "终止时间",
                  value: vuex.createTimeToEnd==""?"":new Date(vuex.createTimeToEnd),
                  ref: "endTime",
                  style: "width:145px;",
                  containerStyle: "width:145px;margin-right: 2%;"
                },{
                  xtype: "button",
                  buttonType: "primary", // 按钮样式
                  buttonText: "查询",
                  style:"width:100px;background:#076dc1;",
                  containerStyle: "width:195px;margin-right: 2%;float:left;",
                  onClick () {
                    let params = {
                      resourceName: vm.$refs.myTable.getRefs("resourceName").$refs.input.value,
                      resourceCode: vm.$refs.myTable.getRefs("resourceCode").$refs.input.value,
                      departmentId: vm.$refs.myTable.getRefs("departmentId").currentValue,
                      status: vm.$refs.myTable.getRefs("status").value,
                      createTimeToStart: vm.$refs.myTable.getRefs("startTime").value,
                      createTimeToEnd: vm.$refs.myTable.getRefs("endTime").value
                    }
                    // 查询条件记录到状态树
                    vm.$store.dispatch('searchTable', params)

                    vm.loadDirData()
                  }
                }]
              }, {
                xtype: "toolbarRow",
                items: [{
                  xtype: "button",
                  buttonType: "primary", // 按钮样式
                  buttonText: "导出",
                  style: "width:135px;background:#076dc1;",
                  containerStyle: "width:135px;margin-right: 2%;float:right;",
                  onClick() {
                    window.open(`${config.siteInfo.sites.file_server_url}/dir/infoResourceExport?token=${localStorage.token}`)
                  }
                }, {
                  xtype: "upload",
                  buttonType: "primary", // 按钮样式
                  buttonText: "导入(不含分类)",
                  style: "width:135px;background:#076dc1;",
                  containerStyle: "width:135px;margin-right: 2%;float:right;",
                  action: `${config.siteInfo.sites.file_server_url}/dir/infoResourceImport?token=${localStorage.token}`,
                  data: {
                    importType: 2,
                    dirId: vm.dirId,
                    token: localStorage.token
                  },
                  onSuccess (response, file, fileList) {
                    // 此处，拿到服务器返回信息，渲染表格数据
                    if(response.code == 10000) {
                      vm.$message.success("导入成功！")
                      vm.loadDirData()
                    }
                    else{
                      vm.$message.error("导入失败！")
                    }
                  }
                }, {
                  xtype: "upload",
                  buttonType: "primary", // 按钮样式
                  buttonText: "导入(含分类)",
                  style: "width:135px;background:#076dc1;",
                  containerStyle: "width:135px;margin-right: 2%;float:right;",
                  action: `${config.siteInfo.sites.file_server_url}/dir/infoResourceImport?token=${localStorage.token}`, //"/test",//`${$config.siteInfo.sites.file_server_url}/dir/infoResourceImport`,
                  ref: "uploadBtn",
                  data: {
                    importType: 1,
                    token: localStorage.token
                  },
                  onSuccess (response, file, fileList) {
                    // 此处，拿到服务器返回信息，渲染表格数据
//                    debugger
                    if(response.code == 10000) {
                      vm.$message.success("导入成功！")

                      vm.loadDirData()
                    }
                    else{
                      vm.$message.error("导入失败！")
                    }
                    //vm.$refs.myTable.getRefs("uploadBtn").submit()
                  }
//                  upload (file) {
////              console.log(vm.$refs.myTable.getRefs("uploadBtn"))
//                    vm.$refs.myTable.getRefs("uploadBtn").submit()
//                  }
                }, {
                  xtype: "button",
                  buttonType: "primary", // 按钮样式
                  buttonText: "添加",
                  style: "width:100px;background:#076dc1;",
                  containerStyle: "width:145px;margin-right: 2%;float:left;",
                  onClick() {
                    if(!vm.dirId){
                      vm.$message.error("请选择一项资源分类！")
                    }
                    else {
                      vm.$router.push({path: '/catalogManage/editResources', query: { dirId: vm.dirId, dirTypeId: vm.dirTypeId || vm.dirId, allDirId: vm.allDirId }})
                    }
                  }
                }, {
                  xtype: "button",
                  buttonType: "danger", // 按钮样式
                  buttonText: "删除",
                  style: "width:100px;",
                  containerStyle: "width:100px;margin-right: 2%;float:left;",
                  onClick() {
                    let arr = []
                    vm.tableRows.forEach(item => {
                      arr.push(item.infoResourceId)
                    })
                    dirAPIs.infoResourceDelete({
                      token: localStorage.token,
                      key: arr.join(",")
                    }).then(({ data }) => {
                      if(data.code == 10000){
                        vm.$message.success("删除信息资源成功！")
                        vm.loadDirData()
                      }
                      else{
                        vm.$message.error(data.msg)
                      }
                    })
                  }
                }]
              }]
            }
          }
        })

      }
    }
  }
</script>
<style>
  .catalogTree{
  	background: #f1f1f1;
  }
  .catalogTree .is-current{
  	background: #fff;
  	color:#2cace2
  }
  .catalogTree .is-current button span{
  	color:#2cace2
  }
  .catalogTree .is-current button:last-child span{
  	color:#e15959
  }
  .catalogContainer{
  	width: 91%;
  	margin: 0 auto;
  }
  .catalogContainer .el-aside{
  	width: 18% !important;
  }
  .catalogContainer .el-aside .el-container{
  	width: 100%;
  	min-width: 200px;
  }
  .catalogContainer .el-main{
  	width: 81%;
  	margin-left:20px ;
  	padding: 0;
  }
  .catalogContainer .moduleBar{
  	width: 100%;
  }
  .catalogContainer .tablebar{
  	width: 100%;
  	margin-top:20px;
  }
  .failDataTable .el-table__header tr{
    background-color: #eeeeee;
  }
</style>
